import subprocess


def kill_processes_by_fuzzy_name(fuzzy_name):
    try:
        # 使用 tasklist 命令获取所有进程信息
        result = subprocess.run(['tasklist'], capture_output=True, text=True)
        processes = result.stdout.splitlines()

        for process in processes:
            if fuzzy_name.lower() in process.lower():
                # 提取进程名
                process_name = process.split()[0]
                try:
                    # 使用 taskkill 命令强制终止进程
                    subprocess.run(['taskkill', '/F', '/IM', process_name], check=True)
                    print(f"成功杀死进程: {process_name}")
                except subprocess.CalledProcessError as e:
                    print(f"杀死进程 {process_name} 时出错: {e}")
    except Exception as e:
        print(f"执行过程中出现错误: {e}")

import psutil
import os

def find_processes_by_name(name_fragment):
    """根据进程名片段模糊查找进程，返回进程ID和程序路径列表"""
    processes = []
    for proc in psutil.process_iter(['pid', 'name', 'exe']):
        try:
            if name_fragment.lower() in proc.info['name'].lower():
                processes.append({
                    'pid': proc.info['pid'],
                    'name': proc.info['name'],
                    'exe': proc.info['exe'] or 'N/A'
                })
        except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
            pass
    return processes

def find_ports_by_pid(pid):
    """根据进程ID查找其开放的端口"""
    ports = []
    try:
        proc = psutil.Process(pid)
        for conn in proc.net_connections(kind='inet'):
            if conn.status == 'LISTEN':
                ports.append({
                    'local_address': f"{conn.laddr[0]}:{conn.laddr[1]}",
                    'type': 'TCP' if conn.type == 1 else 'UDP'
                })
    except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess) as e:
        print(f"无法获取进程 {pid} 的连接信息: {e}")
    return ports

def kill_process_main():
    # 请将下面的字符串替换为你要模糊匹配的进程名
    fuzzy_name_to_match = "Chromedriver"
    kill_processes_by_fuzzy_name(fuzzy_name_to_match)

def find_process_info_main():
    # 1. 模糊查找进程
    name_fragment = "chrome"
    processes = find_processes_by_name(name_fragment)

    if not processes:
        print(f"未找到包含 '{name_fragment}' 的进程")
    else:
        print(f"找到 {len(processes)} 个匹配进程:")
        for idx, proc in enumerate(processes, 1):
            print(f"{idx}. PID: {proc['pid']}, 名称: {proc['name']}, 路径: {proc['exe']}")

        # 2. 选择进程查看端口
        for choice in range(1, len(processes)):
            target_pid = processes[choice - 1]['pid']
            ports = find_ports_by_pid(target_pid)
            if ports:
                print(f"进程 {target_pid} 开放的端口:")
                for port in ports:
                    print(f"  - {port['type']} {port['local_address']}")
            else:
                print(f"XXX 进程 {target_pid} 未开放端口")


if __name__ == "__main__":
    find_process_info_main()